<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd('0',1)">添加权限</el-button>
        </div>
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <!-- 只有页面级别才有添加功能 -->
              <el-button v-if="row.type === 1" type="text" @click="hAdd(row.id,2)">添加</el-button>
              <el-button type="text" @click="hEdit(row)">编辑</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog :visible.sync="showDialog" :title="isEdit? '编辑':'添加'" @closed="resetForm">
        <!-- 表单内容 -->
        <el-form ref="myForm" label-width="100px">
          <el-form-item label="权限名称">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="hSumbit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, delPermission, updatePermission } from '@/api/permisson'
import { transDataToTreeData } from '@/utils/index'
export default {
  name: 'Permission',
  data() {
    // const validCode = (rule, value, callback) => {
    //   // 添加时的校验：code不能重复
    //   let existCodeList = this.originList
    //   if (this.isEdit) {
    //     // 编辑时的校验: code能取自己
    //     existCodeList = this.originList.filter(item => item.id !== this.formData.id)
    //   }
    //   existCodeList.map(it => it.code).includes(value)
    //     ? callback(new Error(value + '已经占用'))
    //     : callback()
    // }

    // const validName = (rule, value, callback) => {
    //   // 添加时的校验： 名字不能取子元素的名字
    //   let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
    //   if (this.isEdit) {
    //     // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
    //     // 找兄弟，排除自己
    //     existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
    //   }
    //   existNameList.map(it => it.name).includes(value)
    //     ? callback(new Error(value + '已经占用'))
    //     : callback()
    // }
    return {
      isEdit: false,
      list: [],
      showDialog: false,
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // rules: {
      //   code: [{ message: '不能为空', required: true, trigger: 'blur' }, { validator: validCode, trigger: 'blur' }],
      //   name: [{ message: '不能为空', required: true, trigger: 'blur' }, { validator: validName, trigger: 'blur' }]
      // }
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    async doEdit() {
      try {
        const res = await updatePermission(this.formData)
        console.log(res, '权限修改成功')
        this.loadPermissionList()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    hEdit(row) {
      this.isEdit = true
      this.showDialog = true
      this.formData = { ...row }
    },
    // 删除
    hDel(id) {
      this.$confirm('你确定要删除吗').then(async() => {
        const res = await delPermission(id)
        console.log(res, '删除权限成功')
        if (res.code !== 10000) this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新渲染数据
        this.loadPermissionList()
      }
      ).catch(error => error)
    },
    // 重置表单
    resetForm() {
      this.$refs.myForm.resetFields()
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
    },
    hSumbit() {
      // 假装有兜底效验
      // this.$refs.myForm.validate(valid => {
      // if (!valid) {
      this.isEdit ? this.doEdit() : this.doAdd()
      // }
    //  })
    },
    async doAdd() {
      try {
        const res = await addPermission(this.formData)
        console.log(res, '权限添加成功')
        this.loadPermissionList()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 区别页面级别和按钮级别的数据并保存
    hAdd(pid, type) {
      this.formData.pid = pid
      this.formData.type = type
      this.showDialog = true
      this.isEdit = false
    },
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log('从后端获取的数据的是', res)
        // 将平铺的数据转化成树形结构的数据
        this.list = transDataToTreeData(res.data)
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>
